
package com.questiono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.sameer.questiono.R;

/**
 * @author sameer
 *
 */
public class PlayScreen extends Activity {
	
	/*private PlayFragment mainFragment;*/
    String TAG_ERROR="error";
    String TAG="PLAY_SCREEN";
    private ProfilePictureView profilePictureView;
    private TextView userNameView,score;
	private String email="",name="",ques,opt1,opt2,opt3,opt4,qno,category,atmpt,overall_correct;
	private int ans,total,correct, points,best;
	private Session session;
	private TextView question,timer;
	//private RadioButton o1,o2,o3,o4;
	private Button o1,o2,o3,o4;
	private RadioGroup radioGroup;
	private CountDownTimer countdown;
	private int butClick=-1;
	
	MediaPlayer mPlayer;
	public static final String PREFS_NAME = "Questiono";  
	// questions JSON url
	private static String URL_QUESTIONS = "http://paradigmcraft.com/questiono/getQuestions.php";
	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();
	// user lists
	ArrayList<HashMap<String, String>> usersList;
	// albums JSONArray
	JSONArray users = null;
	// Progress Dialog
	private ProgressDialog pDialog;
	private ConnectionDetector cd;
	private Sound sound;
	
    
	public ProfilePictureView getProfilePictureView() {
		return profilePictureView;
	}

	public void setProfilePictureView(ProfilePictureView profilePictureView) {
		this.profilePictureView = profilePictureView;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void onClick1(View view)
	{
		butClick=0;
		onSubmit();
	}
	public void onClick2(View view)
	{
		butClick=1;
		onSubmit();
	}
	public void onClick3(View view)
	{
		butClick=2;
		onSubmit();
	}
	public void onClick4(View view)
	{
		butClick=3;
		onSubmit();
	}
	
	
	
	public void onSubmit()
	{
		
		/*int id = radioGroup.getCheckedRadioButtonId();
		RadioButton checkedRadioButton = (RadioButton)radioGroup.findViewById(id);
		int index = radioGroup.indexOfChild(checkedRadioButton);*/
		int index =butClick;
		
	/*	Toast.makeText(getApplicationContext(), ""+id, Toast.LENGTH_SHORT).show();*/
		if (butClick == -1){
		    //no item selected
			Toast.makeText(getApplicationContext(), "SELECT AN ANSWER INORDER TO SUBMIT !", Toast.LENGTH_SHORT).show();
		}
		else{
			
		    if ((index+1) == ans){
		        //Do something with the button
		    	Toast.makeText(getApplicationContext(), "RIGHT ANSWER.", Toast.LENGTH_SHORT).show();
		    	++total;
		    	++correct;
		    	points+=2;
		        sound.playSound(PlayScreen.this, R.raw.angry_bird);
		        score.setText("POINTS \t"+points);
		    }
		    else
		    {
		    	Toast.makeText(getApplicationContext(), "Oops that not right.", Toast.LENGTH_SHORT).show();
		    	++total;
		    	points-=5;
		    	if(points<=0)
		    	{
		    		exit();
		    	}
		    	else
		    	{
		    	sound.playSound(PlayScreen.this, R.raw.yaar);
		    	 score.setText("POINTS \t"+points);
		    	}
		    }
		    
		   
		 //   radioGroup.clearCheck();
		    countdown.cancel();
		    getQuestion();
		    
		    
		}
		//display in short period of time
		
	}
	
	public void exit()
	{

		mPlayer = new MediaPlayer();
        mPlayer = MediaPlayer.create(this, R.raw.dead); 
        mPlayer.start();
        if(total>best)
		{
			best=correct;
		}
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putLong("total", total);
		editor.putLong("correct", correct);
		editor.putLong("best", best);
		// Commit the edits!
		editor.commit();
		//Intent nextScreen = new Intent(getApplicationContext(), HomeScreen.class);
		Intent nextScreen = new Intent(getApplicationContext(), Score.class);
		sound.playSound(PlayScreen.this, R.raw.dead);
		startActivity(nextScreen);
	
	}
	
	public void onFinish(View view)
	{
	/*	mPlayer = new MediaPlayer();
        mPlayer = MediaPlayer.create(this, R.raw.dead); 
        mPlayer.start();*/
        if(total>best)
		{
			best=correct;
		}
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putLong("total", total);
		editor.putLong("correct", correct);
		editor.putLong("best", best);
		
		// Commit the edits!
		editor.commit();
		//Intent nextScreen = new Intent(getApplicationContext(), HomeScreen.class);
		Intent nextScreen = new Intent(getApplicationContext(), Score.class);
		sound.playSound(PlayScreen.this, R.raw.dead);
		startActivity(nextScreen);
		
	}
	
	public void startTimer()
	{
		countdown= new CountDownTimer(45000, 1000) {

		     public void onTick(long millisUntilFinished) {
		    	 timer.setText(millisUntilFinished / 1000+" sec");
		     }

		     public void onFinish() {
		    	 timer.setText("Times Up!");
		    	 total++;
		    	 points-=5;
		    	 getQuestion();
		     }
		  }.start();
	}
	
	
	
	public void getQuestion()
	{
		//Get Next Question
		// Loading Questions JSON in Background Thread
		boolean isInternetPresent;
		cd = new ConnectionDetector(getApplicationContext());
		isInternetPresent=cd.isConnectingToInternet();
	
		if (!isInternetPresent)
		{
			showAlertDialog(PlayScreen.this, "No Internet Connection",
					"You don't have internet connection.", false); 
			Intent nextScreen = new Intent(getApplicationContext(), HomeScreen.class);
			startActivity(nextScreen);
		}else
		{
		new LoadQuestions().execute();
		}
		/*countdown= new CountDownTimer(30000, 1000) {

		     public void onTick(long millisUntilFinished) {
		    	 timer.setText(millisUntilFinished / 1000+" sec");
		     }

		     public void onFinish() {
		    	 timer.setText("Times Up!");
		    	 total++;
		    	 getQuestion();
		     }
		  }.start();
*/
	}
	
	@SuppressWarnings("unused")
	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
		Log.i(TAG,"inside makeRequest");
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    // Set the id for the ProfilePictureView
	                    // view that in turn displays the profile picture.
	                    profilePictureView.setProfileId(user.getId());
	                    email=user.asMap().get("email").toString();
	                    Log.i(TAG,email);
	                    name=user.getName();
	                    // Set the Textview's text to the user's name.
	                    Log.i(TAG,name);
	                    userNameView.setText(getName());
	                    Log.i(TAG,getName());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }

			
	    });
	    request.executeAsync();
	} 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play);
		
		PowerManager powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
		WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
		wakeLock.acquire();
		total=0;
		correct=0;
		best=0;
		points =16;
		
		String fontName= "fonts/RainbowMansion.ttf";
		Typeface tf = Typeface.createFromAsset(getAssets(), fontName);
		String fontScore= "fonts/Disko.ttf";
		Typeface score_tf = Typeface.createFromAsset(getAssets(), fontScore);
		/*ques="The word or phrase that is most nearly similar in meaning to the word :\nTENDENTIOUS";
		opt1="biased";
		opt2="likely";
		opt3="abused";
		opt4="literary";
		ans=1;*/
			
		question= (TextView) findViewById(R.id.question);
		question.setTypeface(tf);
		
		o1=(Button) findViewById(R.id.radio0);
		o2=(Button) findViewById(R.id.radio1);
		o3=(Button) findViewById(R.id.radio2);
		o4=(Button) findViewById(R.id.radio3);
	//	radioGroup=(RadioGroup)findViewById(R.id.radioGroup1);
		score=(TextView)findViewById(R.id.score);
		score.setTypeface(score_tf);
		timer= (TextView)findViewById(R.id.timer);
		
		/*question.setText(ques);
		o1.setText(opt1);
		o2.setText(opt2);
		o3.setText(opt3);
		o4.setText(opt4);*/
		
		
		profilePictureView = (ProfilePictureView) findViewById(R.id.selection_profile_pic);
	    profilePictureView.setCropped(true);
	    userNameView=(TextView) findViewById(R.id.selection_user_name);
	    
	    sound= new Sound();
	    sound.playSound(PlayScreen.this, R.raw.here);
	    
	    //getting username and photo from fb saved details
	    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    String name = settings.getString("name", null);
	    String photoId = settings.getString("photoId", null);
	    String email = settings.getString("email", null);
	    /*total= (int) settings.getLong("total", 0);
	    correct= (int) settings.getLong("correct", 0);*/
	    best= (int) settings.getLong("best", 0);
	    profilePictureView.setProfileId(photoId);
	    userNameView.setText(name);
	    getQuestion();
	    
	    
	/*	makeMeRequest(getSession());*/
	/*	if (savedInstanceState == null) {
		        // Add the fragment on initial activity setup
		        mainFragment = new PlayFragment();
		        getSupportFragmentManager()
		        .beginTransaction()
		        .add(android.R.id.content, mainFragment)
		        .commit();
		    } else {
		        // Or set the fragment from restored state info
		        mainFragment = (PlayFragment) getSupportFragmentManager()
		        .findFragmentById(android.R.id.content);
		    }
	    }*/
		
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	
	// Getting data from Server
	class LoadQuestions extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(PlayScreen.this);
			pDialog.setMessage("Fetching Question ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Albums JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			// getting JSON string from URL
			String json = jsonParser.makeHttpRequest(URL_QUESTIONS, "GET", params);

			// Check your log cat for JSON reponse
			Log.d("Users JSON: ", "> " + json);

			try {
				users = new JSONArray(json);
				Log.i(TAG, "question is ::" + json);
				if (users != null) {
					// looping through All users
					for (int i = 0; i < users.length(); i++) {
						JSONObject c = users.getJSONObject(i);

						// Storing each json item values in variable
						 ques = c.getString("statement");
						 ques= ques.replace("::", "\n\n");
						 opt1 = c.getString("option1");
						 opt2 = c.getString("option2");
						 opt3 = c.getString("option3");
						 opt4 = c.getString("option4");
						 ans = Integer.parseInt(c.getString("answer"));
						 category=c.getString("category");
						 qno=c.getString("qno");
						 atmpt=c.getString("attempts");
						 overall_correct=c.getString("correct");
						 
						 Log.i(TAG,"the question no. is: "+qno);
						 Log.i(TAG,"the category is: "+category);
						 Log.i(TAG,"the total right answers are: "+overall_correct);

						// Temporary allowing self name to appear in order to
						// test the application
						//if (!names.equalsIgnoreCase(""))
					/*	 if (!names.equalsIgnoreCase(name))
						{

							Log.i(TAG, "displaying users::" + names);

							// creating new HashMap
							HashMap<String, String> map = new HashMap<String, String>();

							// adding each child node to HashMap key => value
							map.put("TAG_ID", id);
							map.put("TAG_NAME", names);
							map.put("TAG_EMAIL", email);

							// adding HashList to ArrayList
							usersList.add(map);
						} else {
							Log.i(TAG, "Not showing user ::" + names);

						}*/
					}
				} else {
					Log.d("Questions: ", "null");
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all albums
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					
					question.setText(ques);
					//question.setBackgroundResource(R.drawable.a);
					o1.setText(opt1);
					o2.setText(opt2);
					o3.setText(opt3);
					o4.setText(opt4);
					startTimer();
				/*	ListAdapter adapter = new SimpleAdapter(PlayScreen.this,
							usersList, R.layout.list_item_albums, new String[] {
									TAG_ID, TAG_NAME, TAG_EMAIL }, new int[] {
									R.id.user_id, R.id.user_name,
									R.id.user_email });

					// updating listview
					ListView myList = (ListView) findViewById(android.R.id.list);

					Log.i(TAG, "displaying users" + usersList);

					myList.setAdapter(adapter);
				 												*/
					// getListView().setListAdapter(adapter);
				}
			});

		}

	}
	
	public void showAlertDialog(Context context, String title, String message, Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
		
	}
	
	// Adding Override for the Hardware Back key
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				moveTaskToBack(true);
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
}
